<template>
  <a-layout-sider
    class="p-workbench-sider"
    breakpoint="lg"
    :collapsed-width="200"
    theme="light"
    width="270"
  >
    <div class="p-workbench-sider__logo-container">
      <img src="@/assets/logo.png" alt="logo" class="p-workbench-sider__logo" />
      <img
        src="@/assets/logo-name.png"
        alt="可乐白板"
        class="p-workbench-sider__banner"
      />
    </div>
    <a-menu
      mode="vertical"
      style="height: 84%"
      @select="selectMenuItem"
      v-model:selectedKeys="currentMenuItem"
    >
      <a-menu-item key="团队文件">
        <template #icon>
          <BookOutlined />
        </template>
        <span>团队文件</span>
      </a-menu-item>
      <a-menu-item key="回收站">
        <template #icon>
          <DeleteOutlined />
        </template>
        <span>回收站</span>
      </a-menu-item>
    </a-menu>
    <a-flex
      vertical
      justify="center"
      align="center"
      gap="small"
      class="p-workbench-sider__teamInfo"
      v-show="teamList.length !== 0 && teamData.currentTeamId !== ''"
    >
      <a-select
        v-model:value="teamData.currentTeamId"
        style="max-width: 250px"
        :open="teamData.selectOpen"
        :dropdownMatchSelectWidth="false"
        :bordered="false"
        :field-names="{ title: 'name', value: 'id', label: 'name' }"
        :options="teamList"
        @change="changeTeam"
        @select="() => (teamData.selectOpen = false)"
        @click="() => (teamData.selectOpen = !teamData.selectOpen)"
        @blur="() => (teamData.selectOpen = false)"
      >
        <template #option="{ name, createByMe }">
          <div style="font-size: 0.9rem">{{ name }}</div>
          <div style="font-size: 0.7rem" class="color-grey" v-if="createByMe">
            我拥有的
          </div>
        </template>
        <template #dropdownRender="{ menuNode: menu }">
          <v-nodes :vnodes="menu" />
          <a-divider style="margin: 5px 0" />
          <a-space style="padding: 4px">
            <a-button
              type="link"
              @click="
                () => {
                  createModal.visible = true;
                  teamData.selectOpen = false;
                }
              "
            >
              <template #icon>
                <plus-outlined />
              </template>
              创建新团队
            </a-button>
          </a-space>
        </template>
      </a-select>
      <a-button
        type="text"
        size="small"
        :icon="h(SettingOutlined)"
        class="color-grey"
        @click="toTeamSetting"
      >
        团队设置
      </a-button>
    </a-flex>
  </a-layout-sider>
  <a-modal
    v-model:open="createModal.visible"
    title="创建新的团队"
    @ok="confirmCreate"
    @cancel="cancelCreate"
    :maskClosable="false"
    centered
    :width="420"
    :body-style="{ paddingTop: '24px' }"
    :mask-style="{ backgroundColor: 'rgba(0, 0, 0, 0.2)' }"
  >
    <a-form ref="teamFormRef" :model="createModal" :rules="rules">
      <a-form-item name="teamName">
        <a-input
          v-model:value="createModal.teamName"
          placeholder="输入新的团队名称"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="cancelCreate">取消</a-button>
      <a-button
        key="submit"
        type="primary"
        @click="confirmCreate"
        :loading="createModal.confirmLoading"
      >
        创建
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { defineComponent, h, onMounted, reactive, ref, watch } from 'vue';
import {
  BookOutlined,
  DeleteOutlined,
  PlusOutlined,
  SettingOutlined,
} from '@ant-design/icons-vue';
import { Rule } from 'ant-design-vue/es/form';
import { validateTeamName } from '@/utils/FormRules.ts';
import { message } from 'ant-design-vue';
import operateTeam from '@/apis/operate-team.ts';
import { useTeamStore } from '@/store/index.ts';
import { storeToRefs } from 'pinia';
import { router } from '@/router';
import { storage } from '@/utils/LocalStorage.ts';

const emit = defineEmits({
  // 修改菜单项事件
  changeMenuItem(selectedMenuItemKey: string) {
    return !!(selectedMenuItemKey && selectedMenuItemKey.length !== 0);
  },
});
const teamStore = useTeamStore();
const { teamList, currentTeamId } = storeToRefs(teamStore);
const { getTeamList, setCurrentTeamId } = teamStore;

onMounted(async () => {
  await getTeamList();
  // 解决团队被解散后，本地存储的teamId过期导致获取团队白板和团队成员接口报错的问题
  // 思路：判断本地是否有存储teamId，有的话在渲染侧边栏的时候判断本地存储的teamId是否存在于 我所在的团队列表 中，
  // 如果不存在，那就是过期Id，则清除；如果存在则不做处理
  if (teamStore.currentTeamId) {
    const team = teamStore.teamList.find((item) => {
      return item.id === teamStore.currentTeamId;
    });
    if (!team) {
      teamStore.removeCurrentTeamId();
    }
  }
  teamData.currentTeamId = currentTeamId.value || teamList.value[0].id;
  emit('changeMenuItem', currentMenuItem.value[0]);
  changeTeam(teamData.currentTeamId);
});

// 菜单 数据 start
const currentMenuItem = ref(['团队文件']);
function selectMenuItem(selectedItem: any) {
  emit('changeMenuItem', selectedItem.key);
}
// 菜单 数据 end

// 团队 数据 start
const teamData = reactive({
  selectOpen: false, // 下拉菜单显示
  currentTeamId: '', // 当前所在团队（默认是团队数据的第一项）
});

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});
// 切换团队
function changeTeam(value: string) {
  teamData.selectOpen = false;
  setCurrentTeamId(value);
}
// 团队设置
function toTeamSetting() {
  router.push({ name: 'teamSetting', query: { activeTab: '0' } });
}

// 创建团队表单数据
const createModal = reactive({
  visible: false,
  teamName: '',
  confirmLoading: false,
});
const teamFormRef = ref(null);
// 创建团队表单校验规则
const rules: Record<string, Rule[]> = {
  teamName: [{ validator: validateTeamName, trigger: ['blur', 'change'] }],
};
// 确定创建新团队
function confirmCreate() {
  createModal.confirmLoading = true;
  teamFormRef.value
    .validateFields(['teamName'])
    .then(async (res: any) => {
      const response = await operateTeam.createNewTeam({
        name: res.teamName,
      });
      const { data } = response;
      createModal.confirmLoading = false;
      await getTeamList();
      createModal.visible = false;
      teamData.currentTeamId = data;
      changeTeam(data);
      message.success('新团队创建成功，已切换至新团队');
    })
    .catch((err: any) => {
      createModal.confirmLoading = false;
      console.log(err);
    });
}
// 取消创建
function cancelCreate() {
  createModal.visible = false;
  createModal.teamName = '';
  teamFormRef.value.clearValidate();
}
// 团队 数据 end
</script>

<style scoped lang="scss">
.p-workbench-sider {
  overflow: auto;
  height: 100%;
  border-right: rgb(229, 229, 229) solid 1px;
  .p-workbench-sider__logo-container {
    height: 8%;
    padding: 20px;
    text-align: center;
    .p-workbench-sider__logo {
      pointer-events: none;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      width: 2rem;
      height: 2rem;
    }
    .p-workbench-sider__banner {
      pointer-events: none;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      width: 6rem;
      height: 2.5rem;
    }
  }
  .p-workbench-sider__teamInfo {
    height: 8%;
    border-top: rgb(229, 229, 229) solid 1px;
  }
}
.color-grey {
  color: #9a9a9a;
}
:deep(.ant-select-selection-item) {
  font-size: 1.2rem;
  font-weight: bolder;
}
</style>
